import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex) // vue的插件机制

// Vuex.Store 构造器选项
const store = new Vuex.Store({
    // 为了不和页面或组件的data中的造成混淆，state中的变量前面建议加上$符号
    state: {
        // 用户信息
		$isPc: false,
		$hasLogin: false,
        $userInfo: {},
		$enums: {}
    },
	mutations: {
		isPc(state, device) {
			state.$isPc = device || false
		},
		// 存用户信息
		login(state, provider) {
			state.$hasLogin = true
			state.$userInfo = provider
		},
		// 存token
		loginToken(state, token) {
			uni.setStorageSync('TOKEN', token) 
		},
		// 退出登录
		logout(state) {
			state.$hasLogin = false
			state.$userInfo = {}
			uni.clearStorageSync("TOKEN")
		},
		// 设置枚举
		setEnums(state, enums) {
			state.$enums = enums
		},
	},
	actions: {
		// 设置设备
		isPc({ commit }, device) {
			commit("isPc", device)
		},
		getUserInfo({
			commit,
			state
		}, that) {
			let obj = null;
			let callback = null;
			if (that && that.callback) {
				obj = that.obj;
				callback = that.callback;
			} else {
				obj = that;
			}
			console.log(obj)
			obj.httpGet({
				url: obj.$apis.apiLoginInfos
			}).then(res => {
				if (res.success) {
					commit("login", res.result.user)
					if (callback) {
						setTimeout(() => {
							callback();
						}, 200)
					}
					// 未设置身份提示
					if (!res.result.user || !res.result.user.memberType) {
						uni.showToast({
							title: "未设置身份，请联系管理员!",
							duration: 3000,
							mask: false,
							icon: "none",
							complete: () => {
								if (callback) {
									setTimeout(() => {
										callback()
									}, 3000)
								}
							}
						})
					}
				} else {
					commit("logout")
				}
			}).catch(err => {
				commit("logout")
			})
		},
		logout({ commit, state}) {
			commit("logout");
		},
		setEnums({ commit }, that) {
			let obj = null;
			let callback = null;
			if (that && that.callback) {
				obj = that.obj;
				callback = that.callback;
			} else {
				obj = that;
			}
			obj.httpGet({
				url: obj.$apis.apiGlobalEnums
			}).then(res => {
				if (res.success) {
					commit("setEnums", res.result)
					if (callback) {
						setTimeout(() => {
							callback()
						}, 200)
					}
				}
			})
		}
	}
})

export default store